<template>
  <div class="eryu-up-file">
    <files-item
      :class="item.status"
      v-for="(item, index) in fileList"
      :key="index || item.uuid"
      :index="index"
      :read="read"
      :item="item"
      @onDelete="handleDelete(index)"
    ></files-item>

    <div
      class="eryu-up-item"
      v-if="(isAlone && (fileList.length === 0) & !read) || (!isAlone && !read)"
      v-loading="isAlone && loadingArry.length > 0 ? true : false"
    >
      <el-upload
        ref="upload"
        :action="uploadUrl"
        :file-list="fileList"
        :show-file-list="false"
        :multiple="multiple"
        :headers="headers"
        :data="{
          type: 'logo',
        }"
        :before-upload="beforeUpload"
        :on-success="handleSuccess"
        :on-error="handleError"
      >
        <div class="eryu-up-style">
          <div class="up-icon">
            <i class="el-icon-plus"></i>
          </div>
          <div class="up-name">{{ upText }}</div>
        </div>
      </el-upload>
    </div>
    <div v-else></div>

    <template v-if="!isAlone">
      <div
        class="eryu-up-loading"
        v-for="(item, index) in loadingArry"
        :key="index || item.uuid"
      >
        <div class="loading-nav" v-loading="true"></div>
      </div>
    </template>

    <template v-else></template>

    <slot name="template"></slot>
  </div>
</template>

<script>

import { formatFile, uPformatFile, getFileType } from "@/utils/index";
import filesItem from "./filesItem";
import {getAccessToken,getTenantId} from "@/utils/auth";
export default {
  name: "EryuUpFiles",
  props: {
    // 可以上传的文件类型
    accept: {
      type: String,
      default: "jpg,jpeg,png,doc,docx,xlx,xlsx,pdf,ppt, jepg, rar,zip",
    },

    // 可以上传的文件大小  单位MB 默认2MB
    fileSize: {
      type: Number,
      default: 2,
    },

    // 可以上传的文件数量 默认18张
    size: {
      type: Number,
      default: 18,
    },

    // 是否为只读状态 默认不为读
    read: {
      type: Boolean,
      default: false,
    },

    // 上传按钮文案
    upText: {
      type: String,
      default: "上传照片",
    },

    // 单选还是多选 默认多选
    multiple: {
      type: Boolean,
      default: true,
    },

    //  默认是否单张
    isAlone: {
      type: Boolean,
      default: false,
    },

    // 文件list
    value: {
      type: Array,
      default: () => {
        return [];
      },
    },
  },

  components: { filesItem },

  watch: {
    value: {
      immediate: true,
      handler(newValue, oldValue) {
        this.loadDataByValue(newValue);
      },
    },
  },
  computed: {},
  data() {
    return {
      changeSet: null,
      errorSet: null,
      loadingArry: [],
      fileList: [],
      uploadUrl: process.env.VUE_APP_BASE_API + "/admin-api/infra/file/upload", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getAccessToken(),
        "tenant-id":getTenantId() 
      },
      upLen: 0,
    };
  },

  created() {},

  methods: {
    loadDataByValue(value) {
      clearTimeout(this.changeSet);
      this.changeSet = setTimeout(() => {
        this.fileList = formatFile(value);
      }, 200);
    },

    beforeUpload(file) {
      let fileItem = getFileType(file.name);
      let fileTypeArry = this.accept.split(",");
      let isAccept = fileTypeArry.includes(fileItem.type);
      let isLtFileSize = file.size / 1024 / 1024 < this.fileSize;
      this.upLen = this.uplenAppend();
      let isHaveSize =
        this.size == 1
          ? true
          : this.fileList.length + this.loadingArry.length + this.upLen <
            this.size;

      if (isAccept && isLtFileSize && isHaveSize) {
        this.loadingArry.push({
          name: file.name,
        });
      } else if (!isHaveSize) {
        this.onErrorTimeOut("文件数量不能超过" + this.size + "个!");
      } else {
        let erryText = "";
        erryText += !isLtFileSize ? "大小超过" + this.fileSize + "MB!" : "";
        erryText += !isAccept ? "不支持上传该类型的文件!" : "";

        this.$message({
          message: file.name + erryText,
          type: "error",
        });
      }

      return isAccept && isLtFileSize && isHaveSize;
    },

    uplenAppend() {
      clearTimeout(this.uplenAddSet);
      this.uplenAddSet = setTimeout(() => {
        this.upLen = 0;
      }, 500);
      return this.upLen++;
    },

    handleChange(file, fileList) {
      if (this.size === 1) {
        let arry = [];
        arry.push(this.changeFileFormat(file));
        this.$emit("change", arry);
      } else {
        let arry = JSON.parse(JSON.stringify(this.value));
        arry.push(this.changeFileFormat(file));
        this.$emit("change", arry);
      }
    },

    handleSuccess(response, file, fileList) {
      this.clearLoading();
      const { code, msg } = response;
      this.handleChange(file, fileList);
      if (code !== 0) {
        this.onErrorTip(msg);
      }
    },

    handleError(err, file, fileList) {
      this.onErrorTip("上传出错了，请稍后重试!");
      this.clearLoading();
    },

    onErrorTip(msg) {
     

      this.$message({
        message: msg,
        type: "error",
      });
    },

    onErrorTimeOut(msg) {
      clearTimeout(this.errorSet);
      this.errorSet = setTimeout(() => {
        this.$message({
          message: msg,
          type: "error",
        });
      }, 200);
    },

    clearLoading() {
      if (this.loadingArry.length > 0) {
        this.loadingArry.splice(0, 1);
      }
    },

    handleDelete(index) {
      let arry = JSON.parse(JSON.stringify(this.fileList));
      arry.splice(index, 1);
      this.$emit("change", arry);
    },

    changeFileFormat(file) {
      const { name, size, uid, response } = file;
      const { code, data } = response;
      let status = code === "0" || code === 0 ? "success" : "error";
      let raw = getFileType(name).isImage
        ? URL.createObjectURL(file.raw)
        : undefined;
      return {
        name,
        size,
        uid,
        status,
        isImage: getFileType(name).isImage,
        fileName: name,
       
        fileType: getFileType(name),
        fileUrl:data,
        raw,
      };

    },
  },

  model: { prop: "value", event: "change" },
};
</script>
<style lang="scss" scoped>
.eryu-up-file {
  display: flex;
  flex-wrap: wrap;
}
.eryu-up-style {
  width: 96px;
  height: 102px;
  background: #fbfbfb;
  border-radius: 4px;
  border: 1px solid #d9d9d9;
  text-align: center;
  .up-icon {
    padding: 12px 0px;
    font-size: 28px;
    color: #999999;
  }

  .up-name {
    color: #666666;
    font-size: 12px;
    line-height: 1em;
  }
}

.eryu-up-item {
  padding-left: 20px;

  .eryu-up-img {
    cursor: pointer;
    width: 96px;
    height: 102px;
    background-repeat: no-repeat;
    background-position: 50% 50%;
    background-size: cover;
    background-color: #fbfbfb;
    border-radius: 4px;
    border: 1px solid #d9d9d9;
  }

  .eryu-up-file {
    width: 96px;
    height: 102px;
    background: #fbfbfb;
    border-radius: 4px;
    border: 1px solid #d9d9d9;
    font-size: 14px;
    text-align: center;
    display: block;
    cursor: pointer;

    .file-icon {
      text-align: center;
      width: 100%;
      font-size: 32px;
      display: block;
      padding: 12px 0px;
    }
    .file-name {
      text-align: center;
      padding: 4px 4px;
      font-size: 12px;
      white-space: nowrap;
      line-height: 1em;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }

  &.error {
    .eryu-up-img {
      border: 1px solid red;
    }
    .eryu-up-file {
      border: 1px solid red;
      color: red;
    }
  }
}

.eryu-up-loading {
  padding-left: 20px;
  .loading-nav {
    width: 96px;
    height: 102px;
    background: #fbfbfb;
    border-radius: 4px;
    border: 1px solid #d9d9d9;
  }
}
</style>